<?php


namespace api\blog\controller;


use api\blog\model\OrderModel;
use api\blog\model\UserModel;
use cmf\controller\RestBaseController;
use think\facade\Db;
use think\Request;

class PayController extends RestBaseController
{
    //账户余额支付
    public function walletPay(Request $request)
    {
        $orderId = input('post.order_id');
        $order = OrderModel::find($orderId);
        if (!$order) {
            return error("订单不存在");
        }
        if ($order['status'] != 0) {
            return error("该订单已支付");
        }

        //查询用户
        $user = UserModel::where('id' , $request->userId)->find();
        //判断账户余额是否够
        if ($user['wallet'] < $order['total_price']) {
            return error("账户余额不足");
        }

        Db::startTrans();
        try {
            //1.订单的status修改成1
            $order->status = 1;
            $order->pay_type = '账户余额';
            $order->save();
            $after =  $user['wallet'] - $order['total_price'];
            //2、流水记录
            money_log($order['user_id'],$order['total_price'] , $user['wallet'],$after, 0);

            //3.用户余额修改
            $user->wallet = $after;
            $user->save();

            Db::commit();
            return success('支付成功');
        } catch (\Exception $exception) {
            Db::rollback();
            return error($exception->getMessage());
        }
    }
}